package com.atguigu.ssyx.common.security;

import com.atguigu.ssyx.common.constant.RedisConst;
import com.atguigu.ssyx.common.utils.JwtHelper;
import com.atguigu.ssyx.vo.user.UserLoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequiredArgsConstructor
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    private final RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.从请求头里获取token
        String token = request.getHeader("token");
        log.info("token=======================================:{}", token);
        //2.通过token获取用户id
        if (!StringUtils.isEmpty(token)) {
            Long userId = JwtHelper.getUserId(token);
            //3.从redis获取用户信息
            UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);

            if (userLoginVo != null) {
                //4.将用户信息设置到ThreadLocal中
                AuthContextHolder.setUserId(userLoginVo.getUserId());
                AuthContextHolder.setWareId(userLoginVo.getWareId());

            }

        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {


        //5.在请求结束后，将ThreadLocal中的数据清除
        AuthContextHolder.setUserId(null);
        AuthContextHolder.setWareId(null);

    }
}
